<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="menu-container">
    <el-row v-for="(tree, index) in trees" :key="index">
      <el-col :span='12' v-if="tree[0]">
        <div style="margin-top: 10px; background-color: #e4e7ed;">
          <span style="font-weight: 600;">{{ tree[0].menuName }}</span>
          <el-tree style="margin-top: 10px;" :default-checked-keys="activeMenuIds" @check-change="checkClick"
            :data="[tree[0]]" show-checkbox node-key="id" default-expand-all :props="defaultProps" />
        </div>
      </el-col>
      <el-col :span='12' v-if="tree[1]">
        <div style="margin-top: 10px; background-color: #e4e7ed;">
          <span style="font-weight: 600;">{{ tree[1].menuName }}</span>
          <el-tree style="margin-top: 10px;" :data="[tree[1]]" show-checkbox node-key="id"
            :default-checked-keys="activeMenuIds" @check-change="checkClick" default-expand-all :props="defaultProps" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { _getAllMenuList } from '@/api/generic/menu/menu-api';
import { onMounted, ref, watch } from 'vue';

const defaultProps = {
  children: 'children',
  label: 'menuName',
}

interface MenuInfo {
  id: string;
  menuName: string;
  menuType: 'M' | 'C' | 'B';
  children?: MenuInfo[];
}

const propsConfig = defineProps<{ roleMenuList: MenuInfo[] }>();
const menuListTree = ref<MenuInfo[]>([]);
const alreadyChooseMenus = ref<MenuInfo[]>([]);
const originalActiveMenuIdsData = ref('');
const trees = ref<MenuInfo[][]>([]); // 用于存储拆分后的树
const bindDataMenuIds = ref<string[]>([]);
const activeMenuIds = ref<string[]>([]); //界面渲染使用，当前里面只包含了子节点的id，eg:放入节点id， 那么当前节点和所有子节点也会被勾选
const emits = defineEmits(['clickCallBack']);
onMounted(async () => {
  // 加载所有菜单及模块数据
  const res = await _getAllMenuList();
  menuListTree.value = res.data;
  console.log("所有菜单数据：", menuListTree.value);
  // 拆分树形数据
  splitTrees();
});
const checkClick = (item: MenuInfo, isCheck: boolean, childCheck: boolean) => {
  console.log(item);
  console.log(isCheck);
  console.log(childCheck);
  console.log(alreadyChooseMenus.value);

  // 子节点如果被勾选了，那么当前节点也算被勾选
  if (isCheck || childCheck) {
    // 如果 bindDataMenuIds 中不存在 item.id，则添加
    if (!bindDataMenuIds.value.includes(item.id)) {
      console.log("添加", item.menuName)
      bindDataMenuIds.value.push(item.id);
    }
  } else {
    // 如果 bindDataMenuIds 中存在 item.id，则移除
    const index = bindDataMenuIds.value.indexOf(item.id);
    if (index !== -1) {
      console.log("删除", item.menuName)
      bindDataMenuIds.value.splice(index, 1);
    }
  }
  console.log("初始", originalActiveMenuIdsData.value)
  console.log("操作后", JSON.stringify(bindDataMenuIds.value))
  emits('clickCallBack', {
    original: originalActiveMenuIdsData.value,
    last: JSON.stringify(bindDataMenuIds.value)
  });
};

const loadPage = (vals: MenuInfo[]) => {
  alreadyChooseMenus.value = vals;
  // 根据 alreadyChooseMenus 的 id 更新表格的选中状态
  if (alreadyChooseMenus.value.length > 0) {
    activeMenuIds.value = alreadyChooseMenus.value.map(menu => menu.id);
  } else {
    activeMenuIds.value = [];
  }
  bindDataMenuIds.value = activeMenuIds.value;
  originalActiveMenuIdsData.value = JSON.stringify(activeMenuIds.value);
  //如果当前节点存在子集，视图绑定数据 移除当前节点
  alreadyChooseMenus.value = alreadyChooseMenus.value.filter(item =>{
    return !alreadyChooseMenus.value.some(parent => parent.parentId == item.id)
  })
  console.log("接收到的勾选数据", alreadyChooseMenus.value);
  activeMenuIds.value = alreadyChooseMenus.value.map(menu => menu.id);
};

watch(
  () => propsConfig.roleMenuList,
  async (newVal: MenuInfo[]) => {
    loadPage(newVal);
  },
  { deep: true, immediate: true }
);
// 拆分树形数据为多个树
const splitTrees = () => {
  trees.value = []; // 清空之前的树
  let tempTrees: MenuInfo[] = [];
  menuListTree.value.forEach((item) => {
    // 将每个子节点作为根节点
    const newTree = {
      id: item.id,
      menuName: item.menuName,
      menuType: item.menuType,
      children: item.children || [] // 确保有 children 属性
    };

    tempTrees.push(newTree);
    // 每两个树作为一组
    if (tempTrees.length === 2) {
      trees.value.push(tempTrees);
      tempTrees = []; // 清空临时数组
    }
  });
  // 添加最后一组树
  if (tempTrees.length > 0) {
    trees.value.push(tempTrees);
  }
  console.log("拆分后的树数据:", trees.value);
};
</script>

<style scoped>
.menu-container {
  max-height: 600px;
  overflow-y: auto;
  border: 1px solid #ccc;
  padding: 10px;
}

.tree-row {
  display: flex;
  /* 使用 flexbox 布局 */
  justify-content: space-between;
  /* 在行内均匀分布 */
}
</style>
